import Toast from '@vant/weapp/toast/toast'
var schoolName = "";
var locationName = "";
var showOnce = 0;
import common from "../../js/common.js"
const app = getApp()
var content=''
var phone = 0
var price = 0
var showprice = true
var orderNum =0
var floor = 0
// var zlocation = ""
var ztype=""
var zsex=""
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showDialog:false,
    option1: [
      { text: '标准大小', value: 0 },
      { text: '小包裹', value: 1 },
      { text: '中包裹', value: 2 },
      { text: '大包裹', value: 3 },
    ],
    value1: 0,
    package:0,
    list: ['超重', '超长'],
    result: [],
    btnStatue:true,
    addname:"点击获取发布位置",
    fileList:[],
    videoUrl:"",
    tapIdx:-1,
    radio: '1',
    value: '',
    show: false,
    typeshow:false,
    location:-1,
    type:-1,
    sex:-1,
    isSpecial:false,
    isusecard:false,
    // columns: ['彭桥校区', '瑶湖校区',],
    typecolumns: ['快递','外卖','其他'],
    sexcolumns: ['女寝','男寝','教学楼','图书馆'],
  },

  clickSize(){
    if(showOnce==0)
    {
      this.setData({
        showDialog:true
      })
      showOnce++
    }  
   
  },

  onChanged(event) {
    this.setData({
      result: event.detail,
    });
  },
  toggle(event) {
    const { index } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },


  sexshowPopup()
  {
    this.setData({ sexshow: true });
  },
  sexonCancel() {
    this.setData({ sexshow: false });
  },  
  sexonConfirm(event) {
    const { picker, value, index } = event.detail;
   var pi = event.detail.index
    // console.log(pi)
    this.setData({ 
      sexshow: false,
      sex:pi
    }); 
    if( this.data.sex==0)
    {
      zsex = "女寝"
    }
    if( this.data.sex==1)
    {
      zsex = "男寝"
    }
    if( this.data.sex==2)
    {
      zsex = "教学楼"
    }
    if( this.data.sex==3)
    {
      zsex = "图书馆"
    }
     Toast(`配送类型：${value}`);
    //  console.log(zsex)
  },

  typeshowPopup()
  {
    this.setData({ typeshow: true });
  },
  showPopup() {
    this.setData({ show: true });
  },
  typeonCancel() {
    this.setData({ typeshow: false });
  },  
  typeonConfirm(event) {
    const { picker, value, index } = event.detail;
   var pi = event.detail.index
    console.log(pi)
    this.setData({ 
      typeshow: false,
      type:pi
    }); 
    if( this.data.type==0)
    {
      ztype = "快递"
    }
    if( this.data.type==1)
    {
      ztype = "外卖"
    }
    if( this.data.type==2)
    {
      ztype = "其他"
    }
     Toast(`配送类型：${value}`);
  },
  onClose() {
    this.setData({ show: false,
        showDialog:false
     });
    
  },
  onSwitch1Change(event){
    this.setData({
      package:event.detail
    })
  },
  onConfirm(event) {
    const { picker, value, index } = event.detail;
   var pi = event.detail.index
    // console.log(pi)
    this.setData({ 
      show: false,
      location:pi
    }); 
     Toast(`配送区域：${value}`);
  },

  onCancel() {
    this.setData({ show: false });
  },  

  onClickNav({ detail = {} }) {
    this.setData({
      mainActiveIndex: detail.index || 0,
    });
  },
  onClickItem({ detail = {} }) {
    const activeId = this.data.activeId === detail.id ? null : detail.id;

    this.setData({ activeId });
  },

  //删除图片
  delImg(res){
    // console.log(res)
    var idx =res.detail.index
    this.data.fileList.splice(idx,1);
    this.setData({
      fileList:this.data.fileList
    })
  },
  //处理上传图像
  afterReadImg(res){
    var oldArr = this.data.fileList
    var newArr = oldArr.concat(res.detail.file)
    this.setData({
      fileList : newArr
    })
  },
  //获取用户位置信息
  getAddress(){
      wx.getSetting({
        success:res=>{
          if(res.authSetting['scope.userLocation'])
          {
              this.openMap();
          }else
          {
             wx.authorize({
               scope: "scope.userLocation",
               success:res=>{
                 this.openMap();
               },
               fail:err=>{
                var userAdd = wx.getStorageSync('userAdd')
                if(userAdd){
                  this.getUserLocation()
                }
                  wx.setStorageSync('userAdd', true)
               }
             })
          }
        }
      })
  },
  //当拒绝了以后重新请求授权
  getUserLocation(){
    wx.getSetting({
      success:res=>{
        if(!res.authSetting['scope.userLocation'])
        {
          wx.showModal({
            title:'是否授权获取当前位置',
            content:'只有获取当前位置才能进行操作',
            success:res=>{
              if(res.confirm){
                wx.openSetting({
                  success:res=>{
                    if(res.authSetting['scope.userLocation']){
                      wx.showToast({
                        title: '授权成功',
                        icon: "success"
                      })
                      setTimeout(()=>{
                         this.openMap()
                      },1000)
                     
                    }
                  }
                })
              }
            }
          })
        }
      }
    })
  },
  //打开地图
    openMap()
     {
      wx.chooseLocation({
        success: (res) =>{
          this.setData({
            addName:res.name,
            latitude:res.latitude,
            longitude:res.longitude
          })
          },
      })
     },
     //检测到用户输入内容激活提交按钮
    onChange(event){
    var val = event.detail
      if(val.length>0)
      {
        this.setData({
          btnStatue:false
        })
      }
      else{
        this.setData({
          btnStatue:true
        })
      }
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      schoolName = wx.getStorageSync("schoolName");
      locationName =  wx.getStorageSync("locationName");
     if(schoolName=="延边大学")
     {
       this.setData({
          isSpecial : true
       })
     }
       this.setData({
        tapIdx :options.tapIdx
       })
       if(this.data.tapIdx)
       {

        this.setData({
          type:this.data.tapIdx,
        })
       }
       if( this.data.type==0)
      {
        ztype = "快递"
      }
      if( this.data.type==1)
      {
        ztype = "外卖"
      }
      if( this.data.type==2)
      {
        ztype = "其他"
      }
      console.log(this.data.tapIdx)
      console.log(ztype)
  },
  //提交表单
  addprice(){
    showprice = false
  },
  async onSubmit(res){
     wx.showLoading({
       title: '加载中...',
     })
       content = res.detail.value.content
       phone = res.detail.value.phone
      floor = res.detail.value.floor
      console.log(floor)
      //起价2块 楼层大于3 加一块  超长或超重 加两块
      if(schoolName=="延边大学")
      {
          if(res.detail.value.floor==1)
          {
            price = 6
          }

        else{
          price = 0.2*(res.detail.value.floor-1)+6
          console.log(price)
        }
        if(this.data.package!=0)
        {
          if(this.data.package==1)
          {
            price +=2
          }
          if(this.data.package==2)
          {
            price +=4.5
          }
          if(this.data.package==13)
          {
            price +=6.5
          }
        }
      }
      else
      {
            if(res.detail.value.floor<=3)
            {
              price=2
            }
          else{
            price = 3
          }

          if(this.data.result.length!=0)
          {
            if(this.data.result.length>1)
            {
              price+=(this.data.result.length-1)*2
            }
            
          }
      }  
      if(showprice==true)
      {
        
        return ;
      }
//查询是否有优惠卷
     await wx.cloud.callFunction({
      name:"jiedan_getcard",
      data:{
          check:1
      }
  }).then(res=>{
    if(res.result>0)
    {
      wx.showToast({
        title: '已使用折扣券',
        icon: 'success',
        mask:true
      },800)
        price=price*0.8
        this.setData({
          isusecard:true
        })
        wx.cloud.callFunction({
          name:"jiedan_usecard",
          data:{
              count:res.result-1
          }
        })
    }
    else{
      wx.showToast({
        title: '暂无折扣券',
        icon: 'error',
        mask:true
      },800)
    }
  })


      if(!(/^1[3456789]\d{9}$/.test(phone))){ 
          wx.showToast({
            title: '手机号填写错误',
            icon: 'error',
            mask:true
          },800)
          return false 
      }
      if(!content)
      {
        wx.showToast({
          title: '请填写订单信息',
          icon: 'error',
          mask:true
        },800)
        return false 
      }
      if(!floor)
      {
        wx.showToast({
          title: '请填写楼层数',
          icon: 'error',
          mask:true
        },800)
        return false 
      }
      // if(this.data.location==-1)
      // {
      //   wx.showToast({
      //     title: '请选择配送校区',
      //     icon: 'error',
      //     mask:true
      //   },800)
      //   return false 
      // }
      if(this.data.type==-1)
      {
        wx.showToast({
          title: '请选择配送类型',
          icon: 'error',
          mask:true
        },800)
        return false 
      }
      if(this.data.sex==-1)
      {
        wx.showToast({
          title: '请选择目的地类型',
          icon: 'error',
          mask:true
        },800)
        return false 
      }
       wx.showLoading({
        mask:true,
        title: '数据提交中...',
        success: function() {
          setTimeout(function() {
            //要延时执行的代码
          }, 1000) //延迟时间
        },
      },1000)
     
 
      var _updateTime = Date.now();
     orderNum =String(_updateTime)+String(Math.random()).substr(3,8)
      var addname= this.data.addName
      var userInfo = app.globalData
      var ispick = false
      var state = 0//下单未付款
      var results = this.data.result
      // 获取手机型号
      var subData={
        content,
        addname,
        phone,
        userInfo,
        ispick,
        state,
        price,
        orderNum,
        getopenid:0,
        isarr:0,
        floor,
        type:ztype,
        results,
        isusecard:this.data.isusecard,
        schoolName:schoolName,
        schoolLocation:locationName,
      }
      var { fileList,videoUrl}=this.data
      var d=new Date();
      var year=d.getFullYear();
      var month=d.getMonth()+1
      var day=d.getDate();
      month = month < 10 ? "0" + month : month + ""
      day = day < 10 ? "0" + day : day+""
      var newDate = year+month+day;
      if(fileList.length>0)
      {
        var uploading=fileList.map((item,idx)=>{
          return this.uploadFilePromise("submit_image/" + newDate + "/" + 
          common.guid() + 
          common.gHz(item.url),item)
        })
          Promise.all(uploading).then(res=>{
            var newFileArr = res.map(item=>{
              return item.fileID
            })
            subData.imgUrl = newFileArr  
            this.pushCloud(subData)
          })
          return ;
      }

       this.pushCloud(subData)//纯文字
       wx.hideLoading()
    },
    //上传文件传参
    uploadFilePromise(fileName, chooseResult) {
      return wx.cloud.uploadFile({
        cloudPath: fileName,
        filePath: chooseResult.url
      })
    },

//上传到云存储
    pushCloud(subData){
     var that = this
      wx.cloud.callFunction({
        name:"jiedan_info",
        data: subData,
        success:res=>{
            wx.hideLoading()
            if(res.result.errCode==87014)
            {
              wx.showToast({
                title: '发布内容不符合规范!',
                icon:"none"
              })
              return ;
            }
            wx.hideLoading()
            wx.showToast({
              title: '发布成功',
              icon:'success',
              duration:1000,
              success:function(){
                that.setData({
                  result: [],
                  sex:-1
                })
                  setTimeout(function(){
                    wx.navigateTo({
                      url: '/pages/orderpay/orderpay?content='+content+'&phone='+phone+'&price='+price+'&orderNum='+orderNum,
                    })
                    price=0
                },1000);
              }
            })
           
        }
      })
    },
//提示模块
    showToast(){
      wx.showToast({
        title: '发布成功',
        duration:1000
      })
      
    },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})